package com.itheima.service.impl;

import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.DeptLog;
import com.itheima.pojo.Emp;
import com.itheima.service.DeptLogService;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 部门业务层实现类
 */
@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private DeptLogService deptLogService;
    @Autowired
    private EmpServiceImpl empService;

    /**
     * 查询所有部门
     *
     * @return
     */
    @Override
    public List<Dept> findAll() {
        List<Dept> list = deptMapper.findAll();
        return list;
    }

    @Override
    public void insert(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insert(dept);
    }

    @Override
    public void update(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
    }

    @Override
    //@Transactional
    @Transactional(rollbackFor = Exception.class)//开启事务管理
    //public void deleteById(Integer id) throws Exception {
    public void deleteById(Integer id) {
        try {
            deptMapper.deleteById(id);
            //id = 1/0;
            //throw new Exception("出错啦");
            //empMapper.deleteByDeptId(id);
            //删除部门下员工的工作经历
            List<Emp> empList = deptMapper.findAllEmpByDeptId(id);
            List<Integer> empId = empList.stream().map(emp -> emp.getId()).collect(Collectors.toList());
            empService.delete(empId);
        }finally {
            DeptLog log = new DeptLog();
            log.setCreateTime(LocalDateTime.now());
            log.setDescription("删除"+id+"部门");
            deptLogService.insert(log);
        }
    }

    @Override
    public Dept getById(Integer id) {
        return deptMapper.getById(id);
    }
}
